<?php

class YouNet_View_Helper_FormRichEditor extends Zend_View_Helper_FormTextarea
{
	
	
    public function formRichEditor($name, $value = null, $attribs = null)
    {
		$info = $this->_getInfo($name, $value, $attribs);

		$editorOptions = null;
		if( isset($attribs[YouNet_Form_Element_RichEditor::EDITOR_OPTIONS]) )
		{
			$editorOptions = $attribs[YouNet_Form_Element_RichEditor::EDITOR_OPTIONS];
		}
		unset($attribs[YouNet_Form_Element_RichEditor::EDITOR_OPTIONS]);

        $xhtml	= $this->formTextarea($name, $value, $attribs);
		if( !empty($editorOptions ) )
		{
			$xhtml .= $this->_renderEditor($info, $editorOptions);
		}
		return $xhtml;
    }

	protected function _renderEditor($info, $editorOptions)
	{
		$options = $editorOptions;
		if( $editorOptions instanceof Zend_Config_Ini )
		{
			$options = $editorOptions->toArray();
		}
		if( !empty($options['script_url']) )
		{
			if( !( (strpos($options['script_url'], 'http', 0) === 0)
					|| (strpos($options['script_url'], '//', 0) === 0)
				)
			)
			{
				$options['script_url'] = $this->view->baseUrl($options['script_url']);
			}
		}
		if( !empty($options['content_css']) )
		{
			if( !( (strpos($options['content_css'], 'http', 0) === 0)
					|| (strpos($options['content_css'], '//', 0) === 0)
				)
			)
			{
				$options['content_css'] = $this->view->baseUrl($options['content_css']);
			}
		}
		$script = array();
		$script[]	= '<script>';
		$script[]	= 'jQuery("#'.$info['id'].'").tinymce({';
		$tinymceOptions	= array();
		foreach($options as $key => $value)
		{
			if( is_bool($value) || is_int($value))
			{
				$tinymceOptions[]	= "$key : {$value}";
			}
			else
			{
				$tinymceOptions[]	= "$key : \"{$value}\"";
			}
		}
		if( !empty($info['disable']) )
		{
			$tinymceOptions[]	= 'readonly: true';
		}
		$script[] = implode(','.PHP_EOL, $tinymceOptions);
		//@todo @phutp
//		$script[] = 'setup : function(ed)
//					{
//						ed.onInit.add(function(ed)
//						{
//							//Put some special code here
//							//But not recommended
//						});
//					}';		
		$script[] = '});';
		$script[] = '</script>';
		return implode(PHP_EOL,$script);
	}
}
